package com.example.rabbit.eight;

import com.example.rabbit.util.RabbitMqUtils;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 1. type=direct模式下发送消息到普通交换机
 * 2. 产生死信，发送到死信交换机
 * 3. 死信交换机尝试再次发送
 * <p>
 * 测试流程：启动消费者1，关闭消费者1，启动消费者2，启动生产者，消费者2处理死信消息
 * 死信触发有三种场景：  ttl超时，max-limit限制长度，basicReject拒绝处理消息
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/9 11:33
 * @Version 1.0.0
 * @Description
 **/
public class DeadLetterPublish {
    public static String normalExchangeName = "normal_exchange";
    public static String deadExchangeName = "dead_exchange";
    public static String normalQueueName = "normal_queue";
    public static String deadQueueName = "dead_queue";

    public static void main(String[] args) throws IOException, TimeoutException {

        // 使用超时或者限制队列消息长度，验证死信触发情景1，2
//        useTimeoutAndLimitHandleMessage();
        // 使用拒绝处理消息，验证死信触发情景3
        useRejectHandleMessage();

    }

    /**
     * 使用超时并限制商都处理消息
     *
     * @throws IOException Ioexception
     * @throws TimeoutException 超时异常
     */
    public  static void useTimeoutAndLimitHandleMessage() throws IOException, TimeoutException {
        Channel channel = RabbitMqUtils.getChannel();

        String message = "test信息";
        for (int i = 0; i < 10; i++) {
            channel.basicPublish(normalExchangeName, "normalRoutingKey", null, (message + i).getBytes(StandardCharsets.UTF_8));

        }
        System.out.println(" send message success");
    }

    /**
     * 使用拒绝处理消息
     */
    public  static void useRejectHandleMessage() throws IOException, TimeoutException {
        Channel channel = RabbitMqUtils.getChannel();

        String message = "test信息";
        for (int i = 0; i < 10; i++) {
            channel.basicPublish(normalExchangeName, "normalRoutingKey", null, (message + i).getBytes(StandardCharsets.UTF_8));

        }
        System.out.println(" send message success");
    }
}
